<template>
  <div class="flex items-center justify-center">
    <div class="w-full px-2" style="max-width: 1440px">
      <div
        id="book-list"
        class="p-2 grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4"
      >
        <div class="book" v-for="book in info.results" :key="book.id">
          <a :href="'/book/' + book.id">
            <div class="relative">
              <div
                class=""
                style="min-height: 259px; max-height: 300px; height: 274px"
              >
                <img
                  v-if="book.cover_image_url"
                  :src="book.cover_image_url"
                  alt="封面加载失败"
                  class="h-full w-full object-contain"
                />
                <img
                  v-else
                  src="../assets/images/default_cover.jpg"
                  alt="默认封面"
                  class="h-full w-full object-contain"
                />
              </div>
              <div
                class="rounded absolute bottom-0 right-0 bg-blue-500 px-1 text-sm"
              >
                {{ book.category_name }}
              </div>
            </div>
            <p>{{ book.name }}</p>
            <p class="text-primary-200">作者: {{ book.user_name }}</p>
          </a>
        </div>
      </div>
    </div>
  </div>

  <Page :info="info" />
</template>

<script>
import axios from "axios";
import Page from "@/components/Page.vue";

export default {
  name: "BookList",
  data: function () {
    return {
      info: "",
    };
  },
  components: { Page },
  mounted() {
    this.get_book_data();
  },
  methods: {
    get_book_data: function () {
      let url = "/api/book/"; // /api/book/?page=3&book_name=我
      // 获取page参数值
      const page = Number(this.$route.query.page);
      // 获取search参数
      const search = this.$route.query.search;
      // 获取category_id参数
      const category_id = this.$route.query.category_id;
      const params = new URLSearchParams();

      if (page) {
        params.append("page", page);
      }
      if (search) {
        params.append("name", search);
      }
      if (category_id) {
        params.append("category_id", category_id);
      }
      url = url + "?" + params.toString();

      axios
        .get(url)
        .then((response) => (this.info = response.data))
        .catch((error) => {
          console.log(error);
        });
    },
  },
  watch: {
    // 监听路由的变化
    $route() {
      this.get_book_data();
    },
  },
};
</script>

<style scoped>
.book:hover {
  transform: scale(1.05);
}
</style>
